import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { DatePipe } from '@angular/common';
import { QRScannerModal } from '@modals/qr-scanner/qr-scanner';
import { InstallService } from '@services/data.service/index';
import { MyNoteService } from '@services/myNote.service';
import { GetFromListPipe } from '@pipes/getFormgroup.pipe';
import { PrompBoxtModal } from '@modals/prompt-box/prompt-box';

@Component({
  selector: 'discern-step',
  templateUrl: './discern-step.html',
  styleUrls: ['discern-step.scss']
})
export class DiscernComponent implements OnInit {
  @Input() roomInfo;
  @Input() installData;
  @Input() Step;
  @Output() NextNum: EventEmitter<any> = new EventEmitter();
  CodeInfo = [];
  Card;            // 扫码铭牌
  isCard = true;   // 判断二维码类型是否正确
  constructor(public modalCtrl: ModalController, public installService: InstallService,
    private myNote: MyNoteService, private datePipe: DatePipe, private getFromList: GetFromListPipe
  ) {
  }

  // 初始页面显示
  ngOnInit() {
    console.log('扫码页面房间信息', this.roomInfo);
    this.Step.state = 1;
  }

  // 二维码扫描出的信息
  async scan() {

    // 调试用
    // this.Card = '类型:PIO1900-M;编号:1007;地址:1;'
    // this.CodeInfo = [
    //   { name: '类型', value: 'PIO1900-M' },
    //   { name: '编号', value: '1' },
    //   { name: '地址', value: '1' }
    // ];

    // 正式用
    const modal = await this.modalCtrl.create({
      component: QRScannerModal
    });
    modal.present();
    const data = await modal.onDidDismiss();
    const text = data.data;
    this.Card = text;
    let txt;
    const word = [];
    txt = text.split(';');
    for (let i = 0; i < txt.length; i++) {
      if (txt[i]) {
        txt[i] = txt[i].split(':');
        word.push({
          name: txt[i][0],
          value: txt[i][1]
        });
      }
    }
    this.CodeInfo = word;
    console.log('扫码结果', this.CodeInfo);

    const checkArr = ['类型', '编号', '地址'];
    const isArr = []
    for (const data of this.CodeInfo) {
      data.name = data.name.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
      // 去掉特殊字符
      data.name = data.name.replace(/[\@\#\$\%\^\&\*\{\}\:\"\L\<\>\?]/);
      isArr.push(data.name);
    }
    console.log('检查二维码是否正确', this.arrayEqual(isArr, checkArr));
    if (this.arrayEqual(isArr, checkArr)) {
      const startTime = new Date();
      const Address = parseInt(this.getFromList.transform(this.CodeInfo, 'name', '地址').value.value, 10);
      const Code = parseInt(this.getFromList.transform(this.CodeInfo, 'name', '编号').value.value, 10);
      this.installData.Address = Address;
      this.installData.Code = Code;
      this.installData.startTime = this.datePipe.transform(startTime, 'yyyy-MM-dd HH:mm');
      if (this.roomInfo.Type === 0) {
        if (this.getFromList.transform(this.CodeInfo, 'name', '类型').value.value !== '数据栈') {
          this.myNote.MyNotice('请扫描 “' + '数据栈' + '” 这种设备！');
        } else {
          this.toTwo(this.CodeInfo);
        }
      } else {
        if (this.getFromList.transform(this.CodeInfo, 'name', '类型').value.value !== this.roomInfo.device.meterModelName) {
          this.myNote.MyNotice('请扫描 “' + this.roomInfo.device.meterModelName + '” 这种设备！');
        } else {
          this.installService.checkMeter(this.roomInfo.device.areaId, this.roomInfo.parameter.UID,
            this.roomInfo.device.meterId, this.roomInfo.device.pid, this.installData.Address).subscribe(async res => {
              if (!res.success) {
                if (res.data === 200) {
                  const modal = await this.modalCtrl.create({
                    component: PrompBoxtModal,
                    componentProps: { isCheck: true, checkInfo: '仪表地址已重复，请重新扫码！' }
                  });
                  modal.present();
                } else {
                  this.toTwo(this.CodeInfo);
                }
              } else {
                this.myNote.MyNotice(res.message);
              }
            });
        }
      }
    } else {
      this.myNote.MyNotice('请扫描正确的二维码');

    }
  }

  arrayEqual(arr1, arr2) {
    if (arr1 === arr2) return true;
    if (arr1.length != arr2.length) return false;
    for (var i = 0; i < arr1.length; ++i) {
      if (arr1[i] !== arr2[i]) return false;
    }
    return true;
  }


  // 切换页面
  toTwo(info) {
    if (info) {
      this.Step.state = 2;
    } else {
      this.myNote.MyNotice('请先安装数据栈');
    }
  }

  // 切换步骤
  toNext(i) {
    this.Step.now = i;
    this.installData.step = 1;
    this.installData.state = 1;
    this.installData.areaId = this.roomInfo.device.areaId;
    this.installData.meterId = this.roomInfo.device.meterId;
    this.installData.data1 = this.Card;
    this.installService.saveInstallData(this.installData.areaId, this.installData.meterId, this.installData);
    this.NextNum.emit(this.Step.now);
  }

}
